import Mock from "mockjs"
// 内存模拟数据
const arr = []
for (let i = 0; i < 10; i++) {
  arr.push({
    id: Mock.mock("@id"),
    name: Mock.mock("@cname"),
    place: Mock.mock("@county(true)"),
  })
}
export default [
  {
    url: "/list",
    method: "get",
    response: () => {
      return arr
    },
  },
  // {
  //   url: "/add",
  //   method: "post",
  //   response: (body) => {
  //     const newLength = arr.unshift({
  //       id: Date.now(),
  //       name: body.name,
  //       place: body.place
  //     })
  //     if(newLength > 0) {
  //       return { success: true }
  //     } else {
  //       return { success: false }
  //     }
      
  //   },
  // },
    {
    url: "/add",
    method: "post",
    response: (req) => {
      try {
        const { name, place } = req.body;
        
        // 参数验证
        if (!name || !place) {
          return { success: false, message: "缺少必要参数" };
        }
        
        const newItem = {
          id: Mock.mock("@id"), // 保持ID类型一致
          name,
          place
        };
        
        arr.unshift(newItem); // 添加到数组开头
        
        return { 
          success: true, 
          data: newItem, 
          message: "添加成功" 
        };
      } catch (error) {
        return { success: false, message: "添加失败", error: error.message };
      }
    },
  },
  {
    url: "/del/:id",
    method: "delete",
    response: (req) => {
      const index = arr.findIndex((item) => item.id === req.query.id)
      if (index > -1) {
        arr.splice(index, 1)
        return { success: true }
      } else {
        return { success: false }
      }
    },
  },
  {
    url: "/edit/:id",
    method: "patch",
    response: ({ query, body }) => {
      const item = arr.find((item) => item.id === query.id)
      if (item) {
        item.name = body.name
        item.place = body.place
        return { success: true }
      } else {
        return { success: false }
      }
    },
  },
]
